package com.jiming.webrpc.firewall;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
/**
 * 操作win10防火墙入站规则（需要管理员身份才能运行）
 * @author straw
 */
public class Win10FirewallUtile {
	public static String java_rule_name = "Java(TM) Platform SE binary";
	
	/**
	 * 给进程名称添加入站规则（任何规则、任何协议、任何端口）
	 * @param name
	 */
	public static boolean addRuleByName(String name) {
		if(haveInputRuleByName(name)) {
			//如果已经存在了该规则，就放弃本次操作
			return true;
		}
		
		Process process = null;
		try {
			process = Runtime.getRuntime().exec("netsh advfirewall firewall add rule name= \"" + name + "\" dir=in action=allow protocol=UDP localport=any");
			return true;
		} catch (IOException e) {
			e.printStackTrace();
		}finally {
			if(process != null) {
				process.destroy();
			}
			
		}
		
		return false;
	}
	
	
	/**
	 * 检查防火墙是否已经添加了入站规则
	 * @param name
	 * @return
	 */
	public static boolean haveInputRuleByName(String name) {
		boolean flag = false;
		BufferedReader reader = null;
		Process process = null;
		try {
			process = Runtime.getRuntime().exec("netsh advfirewall firewall show rule name=\"" + name + "\"");
			
			StringBuilder v = new StringBuilder();
			reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
			String line = null;
			while((line = reader.readLine()) != null) {
				v.append(line);
			}
			if(v.toString().contains(name)) {
				flag = true;
			}
		} catch (IOException e) {
			e.printStackTrace();
		}finally {
			if(reader != null) {
				try {
					reader.close();
				} catch (IOException e) {
				}
			}
			
			if(process != null) {
				process.destroy();
			}
			
		}
		
		return flag;
	}
	
	
}
